import accounting from 'accounting';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Select } from 'antd';
import uuid from 'es6-uuid';
import _ from 'lodash';
import React, { PureComponent } from 'react';

import { TableC, InputNumberC, SecuritiesCodeC, codeType, NoDataMaskC } from '../../../../comps';

const FormItem = Form.Item;

@Form.create()
class InBankBondInfoC extends PureComponent {
  constructor() {
    super();
    this.state = {
      isShow: false,
      dataSource: [], // 表格中渲染的数据
      isEdit: false,
      isData: false, // 无数局的蒙尘时候蒙尘展示
      record: undefined, // 回填modal框用的对象
      account: '--', // 总计数据
      isAdd: false,
      BuybackCodeRule: true,
    };
  }

  componentDidMount() {
    this.props.onRef(this);
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { portfolio, direct, trustee, productGroupId } = nextProps;
    if ((portfolio !== undefined || productGroupId != undefined) && trustee !== undefined && direct !== undefined) {
      if (this.props.portfolio !== portfolio || this.props.direct !== direct || this.props.trustee !== trustee || this.props.productGroupId != productGroupId) {
        this.setState({
          dataSource: [],
          isEdit: false,
          isAdd: false,
        });
      }
    }
  }

  // 持仓双击事件
  addNewPledgeBond = (reocrd) => {
    if (this.state.isAdd || this.state.isEdit) {
      message.warning('表格处于编辑状态，禁止新增');
      return;
    }
    const { positionArr } = this.props;
    const data = positionArr.find((item) => item.pledgeBondCode == reocrd.pledgeBondCode);
    const newDataSource = _.cloneDeep(this.state.dataSource);
    newDataSource.unshift({
      uid: uuid(32),
      tradingcode: data.pledgeBondCode,
      secuabbr: data.pledgeBondName,
      amount: data.t0Number,
      isEdit: true,
    });
    newDataSource.map((item) => (item.isDisabled = true));
    this.setState({
      dataSource: newDataSource,
      isAdd: true,
    });
  };

  // 点击新增
  handleClick = () => {
    if (this.state.isAdd || this.state.isEdit) {
      message.warning('表格处于编辑状态，禁止新增');
      return;
    }
    const newDataSource = _.cloneDeep(this.state.dataSource);
    newDataSource.unshift({
      uid: uuid(32),
      isEdit: true,
    });
    newDataSource.map((item) => (item.isDisabled = true));
    this.setState({
      dataSource: newDataSource,
      isAdd: true,
    });
  };

  // 删除质押券
  delete = (record) => {
    const { dataSource } = this.state;
    const newArr = _.cloneDeep(dataSource);
    const newData = newArr.filter((item) => item.uid != record.uid);
    const newArrs2 = _.cloneDeep(newData.filter((item) => item.tradingcode !== '总计'));
    if (newArrs2 && newArrs2.length) {
      const account = this.getAccount(newArrs2);
      newArrs2.push({
        tradingcode: '总计',
        secuabbr: '', // 质押券名称
        pledgeAmount: '', // 质押券数量
        pledgeRatio: '', // 折扣率
        valuationPrice: '', // 债券券面金额
        denomination: account, // 成交金额
        uid: uuid(32), // 表格行唯一标识符-删除编辑使用
      });

      this.setState({
        dataSource: newArrs2,
        account,
      });
      this.props.changeFee(newArrs2?.length - 1, account);
      this.props.account(account);
    } else {
      this.setState({
        dataSource: [],
      });
      this.props.account();
      this.props.changeFee(0);
    }
  };

  // 保存
  save = (record) => {
    const {
      form: { validateFields },
      direct,
    } = this.props;
    const { dataSource } = this.state;
    const newData = _.cloneDeep(dataSource);
    validateFields((err) => {
      if (!err) {
        if (record.pledgeAmount == 0) {
          message.error('质押券数量需大于0');
          return;
        }
        if (direct == '2') {
          if (Number(record.pledgeAmount) > Number(record.amount)) {
            message.warning('融资回购时质押券数量不能大于T+0可用数量');
            return;
          }
        }
        const isRe = newData.filter((item) => item.tradingcode == record.tradingcode);
        if (isRe?.length != 1) {
          message.warning('质押券信息重复');
          return;
        }
        if (newData && newData.length && newData[newData.length - 1].tradingcode !== '总计') {
          newData.push({
            tradingcode: '总计',
            secuabbr: '',
            pledgeAmount: '',
            pledgeRatio: '',
            valuationPrice: '',
            denomination: 0,
            uid: uuid(32),
          });
        }
        newData.map((item) => {
          if (item.uid == record.uid) {
            item.isEdit = undefined;
          }

          if (item.tradingcode == '总计') {
            if (this.state.isEdit) {
              // 编辑时计算总计减去原来的数据
              // eslint-disable-next-line no-mixed-operators
              item.denomination = item.denomination + record.denomination - this.state.editDataSource.denomination;
            } else {
              item.denomination += record.denomination;
            }
          }
          item.isDisabled = undefined;
        });
        this.setState({
          dataSource: newData,
          isAdd: false,
          isEdit: false,
        });
        this.props.changeFee(newData?.length - 1, newData[newData?.length - 1]?.denomination);
        this.props.account(newData[newData?.length - 1]?.denomination);
      }
    });
  };

  // 点击取消
  cancel = (record) => {
    if (this.state.isAdd) {
      const newData = this.state.dataSource.filter((item) => item.uid != record.uid);
      newData.map((item) => (item.isDisabled = undefined));
      this.setState({
        dataSource: newData,
        isAdd: false,
        isEdit: false,
      });
    } else {
      this.setState({
        dataSource: this.state.dataSource.map((item) => {
          if (item.uid == record.uid) {
            return this.state.editDataSource;
          }
          item.isDisabled = undefined;
          return item;
        }),
        isAdd: false,
        isEdit: false,
      });
    }
  };

  // 编辑某条,数据回填
  edit = (record) => {
    const { dataSource } = this.state;
    const newDataSource = _.cloneDeep(dataSource);
    const newData = newDataSource.find((item) => item.uid == record.uid);
    this.state.dataSource.map((item) => {
      if (item.uid == record.uid) {
        item.isEdit = true;
      }
      item.isDisabled = true;
    });
    this.setState({
      editDataSource: newData,
      dataSource: this.state.dataSource,
      isEdit: true,
    });
  };

  // 融资质押券代码改变
  zyqdmOnChange = (e, record) => {
    const {
      positionArr,
      form: { setFieldsValue },
    } = this.props;
    const holdData = positionArr.find((item) => item.pledgeBondCode == e);
    this.state.dataSource.map((item) => {
      if (item.uid == record.uid) {
        item.tradingcode = holdData?.pledgeBondCode;
        item.secuabbr = holdData?.pledgeBondName;
        item.pledgeAmount = undefined;
        item.pledgeRatio = undefined;
        item.amount = holdData?.t0Number;
        item.valuationPrice = undefined;
        item.denomination = undefined;
      }
    });
    setFieldsValue({
      pledgeAmount: '',
      pledgeRatio: '',
    });
  };

  // 融券质押券代码改变
  securitiesCodeChange = (e, record) => {
    const {
      form: { setFieldsValue },
    } = this.props;
    this.state.dataSource.map((item) => {
      if (item.uid == record.uid) {
        item.tradingcode = e?.tradingCode;
        item.secuabbr = e?.secuabbr;
        item.exchangeCode = e?.exchangeCode;
        item.pledgeAmount = undefined;
        item.pledgeRatio = undefined;
        item.valuationPrice = undefined;
        item.denomination = undefined;
      }
    });
    setFieldsValue({
      pledgeAmount: '',
      pledgeRatio: '',
    });
  };

  // 质押券数量改变
  zyqssOnChange = (e, record) => {
    const {
      form: { getFieldValue },
    } = this.props;
    const isTradingCode = !!getFieldValue('tradingcode');
    // 只有选择了质押券代码才进行计算操作

    // 如果质押券rule必填规则生效 走原来的规则 ， 不生效时不需要判断是否选择了质押券代码
    if (this.state.BuybackCodeRule) {
      if (isTradingCode) {
        if (e == 0) {
          this.state.dataSource.map((item) => {
            if (item.uid == record.uid) {
              item.valuationPrice = undefined;
              item.denomination = undefined;
              item.pledgeAmount = e;
            }
          });
        } else {
          this.state.dataSource.map((item) => {
            if (item.uid == record.uid) {
              item.valuationPrice = e * 100;
              item.pledgeAmount = e;
            }
          });
          if (getFieldValue('pledgeRatio')) {
            this.state.dataSource.map((item) => {
              if (item.uid == record.uid) {
                // 成交金额=质押券数量*100*折算率/100
                // eslint-disable-next-line no-mixed-operators
                item.denomination = (e * 100 * getFieldValue('pledgeRatio')) / 100;
              }
            });
          }
        }
      }
    } else if (e == 0) {
      this.state.dataSource.map((item) => {
        if (item.uid == record.uid) {
          item.valuationPrice = undefined;
          item.denomination = undefined;
          item.pledgeAmount = e;
        }
      });
    } else {
      this.state.dataSource.map((item) => {
        if (item.uid == record.uid) {
          item.valuationPrice = e * 100;
          item.pledgeAmount = e;
        }
      });
      if (getFieldValue('pledgeRatio')) {
        this.state.dataSource.map((item) => {
          if (item.uid == record.uid) {
            // 成交金额=质押券数量*100*折算率/100
            // eslint-disable-next-line no-mixed-operators
            item.denomination = (e * 100 * getFieldValue('pledgeRatio')) / 100;
          }
        });
      }
    }
  };

  // 折算比率改变
  zsblOnChange = (e, record) => {
    const {
      form: { getFieldValue },
    } = this.props;
    // 券面总额有值并且折算比率大于0小于100  计算成交金额
    if (getFieldValue('pledgeAmount') && Number(e) > 0 && Number(e) <= 100) {
      this.state.dataSource.map((item) => {
        if (item.uid == record.uid) {
          // 成交金额=质押券数量*100*折算率/100
          // eslint-disable-next-line no-mixed-operators
          item.denomination = (e * 100 * getFieldValue('pledgeAmount')) / 100;
          item.pledgeRatio = e;
        }
      });
    }
    if (Number(e) == 0) {
      this.state.dataSource.map((item) => {
        if (item.uid == record.uid) {
          item.denomination = undefined;
        }
      });
    }
    if (Number(e) > 100) {
      this.state.dataSource.map((item) => {
        if (item.uid == record.uid) {
          item.pledgeRatio = 100;
        }
      });
    }
  };
  /** *
   *
   * @param[bool] rule
   */
  setBuybackCodeRule = (rule) => {
    this.setState({ BuybackCodeRule: rule });
  };
  // 优化页面Columns的渲染
  changeColumns = () => {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const pledgeBondCodeWidths = 200; // 质押券列宽
    let pledgeAmountWidths = 105; // 质押券数量列宽
    let conversionRateWidths = 110; // 折算比例列宽
    if (this.state.isEdit || this.state.isAdd) {
      // 新增或编辑状态需要改变列宽
      pledgeAmountWidths = 160;
      conversionRateWidths = 140;
    } else {
      pledgeAmountWidths = 105;
      conversionRateWidths = 110;
    }
    const columns = [
      {
        title: '质押券',
        key: 'tradingcode',
        width: pledgeBondCodeWidths,
        render: (val, record) => {
          if (record.isEdit) {
            if (this.props.direct == '2') {
              return (
                <FormItem>
                  {getFieldDecorator('tradingcode', {
                    initialValue: val ? `${record.tradingcode}-${record.secuabbr}` : null,
                    rules: this.state.BuybackCodeRule
                      ? [
                          {
                            required: true,
                            message: `请选择质押券`,
                          },
                        ]
                      : this.state.BuybackCodeRule,
                  })(
                    <Select
                      allowClear
                      onChange={(e) => this.zyqdmOnChange(e, record)}
                      style={{ width: '100%' }}
                      placeholder='请选择'
                      filterOption={(
                        input,
                        option, // 模糊搜索value 和 title
                      ) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 || option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                      showSearch
                    >
                      {this.props.positionArr?.map((item) => (
                        <Select.Option value={item.pledgeBondCode}>{`${item.pledgeBondCode}-${item.pledgeBondName}`}</Select.Option>
                      ))}
                      {/* eslint-disable react/jsx-indent */}
                    </Select>,
                  )}
                </FormItem>
              );
            }
            return (
              <SecuritiesCodeC
                form={this.props.form}
                initialValue={val ? `${record.exchangeCode}-${record.tradingcode}` : null}
                dataIndex='tradingcode'
                titleDisplay={false}
                codeType={codeType.zq}
                queryItems={{
                  exchangeCode: '113',
                  clientCode: this.props.trustee,
                }}
                onChange={(e) => this.securitiesCodeChange(e, record)}
                rules={
                  this.state.BuybackCodeRule
                    ? [
                        {
                          required: true,
                          message: '请选择代码!',
                        },
                      ]
                    : this.state.BuybackCodeRule
                }
                positionBody
              />
            );
          }
          if (val == '总计') {
            return val;
          }
          return val ? `${val}-${record.secuabbr}` : '--';
        },
      },
      {
        title: '质押券数量',
        key: 'pledgeAmount',
        type: 'number',
        align: 'right',
        width: pledgeAmountWidths,
        render: (val, record) => {
          if (record.isEdit) {
            return (
              <InputNumberC
                form={this.props.form} // form对象
                dataIndex='pledgeAmount'
                unit='张'
                min={0}
                precision={0}
                initialValue={val || null}
                splitStyle
                onChange={(e) => this.zyqssOnChange(e, record)}
                rules={[
                  {
                    required: true,
                    message: '请输入质押券数量',
                  },
                ]}
              />
            );
          }
          if (record.tradingcode == '总计') {
            return '';
          }
          return accounting.formatNumber(Number(val), 0);
        },
      },
      {
        title: '折算率(%)',
        key: 'pledgeRatio',
        width: conversionRateWidths,
        align: 'right',
        render: (val, record) => {
          if (record.isEdit) {
            return (
              <InputNumberC
                form={this.props.form} // form对象
                dataIndex='pledgeRatio'
                unit='%'
                min={0.01}
                max={100}
                precision={2}
                initialValue={val || null}
                onChange={(e) => this.zsblOnChange(e, record)}
                rules={[
                  {
                    required: true,
                    message: '请输入折算率',
                  },
                ]}
              />
            );
          }
          if (record.tradingcode == '总计') {
            return '';
          }
          return Number(val).toFixed(2);
        },
      },
      // 交易方向为“融资回购”时，展示该列
      ...(this.props.direct == '2'
        ? [
            {
              title: '可用数量',
              key: 'amount',
              width: '105px',
              align: 'right',
              render: (val, record) => {
                if (record.tradingcode == '总计') {
                  return '';
                }
                return accounting.formatNumber(Number(val), 0);
              },
            },
          ]
        : []),
      {
        title: '质押券券面金额(元)',
        key: 'valuationPrice',
        width: '190px',
        align: 'right',
        render: (val, record) => {
          if (record.tradingcode == '总计') {
            return '';
          }
          if (val) {
            return accounting.formatNumber(Number(val), 2);
          }
          return '--';
        },
      },
      {
        title: '成交金额(元)',
        key: 'denomination',
        type: 'money',
        width: '180px',
      },
      ...(this.props.type != 3 && this.props.type != 4
        ? [
            {
              title: '操作',
              dataIndex: 'operate',
              key: 'operate',
              type: 'operate',
              fixed: 'right',
              width: 110,
              operates: [
                {
                  title: '编辑',
                  onClick: (record, index) => this.edit(record, index),
                  rules: {
                    hide: {
                      items: [
                        {
                          key: 'isEdit',
                          value: [undefined],
                          relation: ['!='],
                        },
                        {
                          key: 'tradingcode',
                          value: ['总计'],
                          relation: ['='],
                        },
                      ],
                      relation: 'or',
                    },
                    disabled: {
                      items: [
                        {
                          key: 'isDisabled',
                          value: [undefined],
                          relation: ['!='],
                        },
                      ],
                    },
                  },
                },
                {
                  title: '删除',
                  onClick: (record, index) => this.delete(record, index),
                  rules: {
                    hide: {
                      items: [
                        {
                          key: 'isEdit',
                          value: [undefined],
                          relation: ['!='],
                        },
                        {
                          key: 'tradingcode',
                          value: ['总计'],
                          relation: ['='],
                        },
                      ],
                      relation: 'or',
                    },
                    disabled: {
                      items: [
                        {
                          key: 'isDisabled',
                          value: [undefined],
                          relation: ['!='],
                        },
                      ],
                    },
                  },
                },
                {
                  title: '保存',
                  onClick: (record, index) => this.save(record, index),
                  rules: {
                    hide: {
                      items: [
                        {
                          key: 'isEdit',
                          value: [undefined],
                          relation: ['='],
                        },
                        {
                          key: 'tradingcode',
                          value: ['总计'],
                          relation: ['='],
                        },
                      ],
                      relation: 'or',
                    },
                  },
                },
                {
                  title: '取消',
                  onClick: (record, index) => this.cancel(record, index),
                  rules: {
                    hide: {
                      items: [
                        {
                          key: 'isEdit',
                          value: [undefined],
                          relation: ['='],
                        },
                        {
                          key: 'tradingcode',
                          value: ['总计'],
                          relation: ['='],
                        },
                      ],
                      relation: 'or',
                    },
                  },
                },
              ],
            },
          ]
        : []),
    ];
    return columns;
  };

  // 交收或详情时展示的表格数据
  getDataSource = (info) => {
    const tradeNum = `trade${info.type}`;
    const arr = _.cloneDeep(info[tradeNum].zgPledgeVo);
    if (arr && arr.length) {
      const account = this.getAccount(arr);
      arr.push({
        tradingcode: '总计',
        secuabbr: '', // 质押券名称
        pledgeAmount: '', // 质押券数量
        pledgeRatio: '', // 折扣率
        valuationPrice: '', // 债券券面金额
        denomination: account, // 成交金额
        id: uuid(32), // 表格行唯一标识符-删除编辑使用
      });
    }
    return arr;
  };

  // 展示质押券表格以及新增按钮
  showTable = () => {
    const { type, infoData, isDisabled } = this.props;
    const dataSources =
      type == '1' || type == '2' || type == 10 || type == 11 || type == 12
        ? isDisabled
          ? [
              {
                tradingcode: '张海涛',
                pledgeAmount: '123',
                pledgeRatio: '123',
                valuationPrice: '123',
                denomination: '123',
              },
            ]
          : this.state.dataSource
        : this.getDataSource(infoData);
    const newcolumns = this.changeColumns();
    return (
      <div style={{ position: 'relative' }}>
        {
          <div style={{ marginTop: '10px' }}>
            <TableC
              columns={newcolumns}
              dataSource={dataSources}
              hidePage
              rowKey={type == '1' || type == '2' || type == 10 || type == 11 ? 'uid' : 'id'}
              scroll={{
                x: '1050px',
                y: '200px',
              }}
            />
          </div>
        }
        {isDisabled && (type == '1' || type == '2' || type == 10 || type == 11 || type == 12) ? (
          <div>
            <NoDataMaskC height='100%' title={type == 12 ? '请选择产品组，托管机构，交易方向，加载数据！' : '请选择组合，托管机构，交易方向，加载数据！'} />
          </div>
        ) : null}
      </div>
    );
  };

  // 抛出质押券信息
  getData = () => {
    const { dataSource } = this.state;
    const data = _.cloneDeep(dataSource);
    let account;
    let datas = [];
    let query = {};
    if (this.state.isAdd || this.state.isEdit) {
      message.error('请先保存质押券信息');
      return undefined;
    }
    if (data.length) {
      datas = _.take(data, data.length - 1);
      account = dataSource[dataSource.length - 1].denomination;
      query = {
        list: datas,
        total: account,
      };
    } else if (this.props.direct == 1) {
      // 融券回购，质押券非必填
      query = {
        list: [],
        total: 0,
      };
    } else {
      // message.warning('质押券信息不能为空')
      // datas = undefined;
      // query = undefined;
    }
    return query;
  };

  // 获取总计
  getAccount = (arr) => {
    const data = _.cloneDeep(arr);
    const numArr = []; // 存放成交金额的数组
    let account = '--'; // 成交金额总额
    const getSum = (
      total,
      num, // 获取数组的合
    ) => total + num;
    if (data && data.length) {
      data.map((item) => {
        numArr.push(item.denomination);
      });
      account = numArr.reduce(getSum);
    }
    this.props.account(account);
    return account;
  };

  // 清空质押券
  setTable = () => {
    this.setState({ dataSource: [] });
  };

  render() {
    return (
      <>
        <div>
          <>{this.showTable()}</>
        </div>
      </>
    );
  }
}

export default InBankBondInfoC;
